package com.ruoyi.web.controller.credit;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.CreditUserInfo;
import com.ruoyi.system.service.ICreditUserInfoService;
import com.ruoyi.system.service.ICreditStatisticsService;
import com.ruoyi.system.mapper.CreditUserInfoMapper;
import com.ruoyi.system.mapper.CreditServiceConfigMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ICreditNewsService;
import com.ruoyi.system.domain.CreditNews;
import com.ruoyi.system.service.ICreditServiceConfigService;
import com.ruoyi.system.domain.CreditServiceConfig;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.utils.SecurityUtils;
import java.math.BigDecimal;
import com.ruoyi.system.domain.CreditScoreHistory;
import com.ruoyi.system.mapper.CreditScoreHistoryMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 信用生活系统管理员功能控制器
 * 
 * @author ruoyi
 * @date 2024-01-26
 */
@RestController
@RequestMapping("/credit/admin")
public class CreditAdminController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(CreditAdminController.class);

    @Autowired
    private ICreditUserInfoService creditUserInfoService;

    @Autowired
    private ICreditStatisticsService creditStatisticsService;

    @Autowired
    private CreditUserInfoMapper creditUserInfoMapper;

    @Autowired
    private CreditServiceConfigMapper creditServiceConfigMapper;

    @Autowired
    private ICreditNewsService creditNewsService;

    @Autowired
    private ICreditServiceConfigService creditServiceConfigService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private CreditScoreHistoryMapper creditScoreHistoryMapper;

    /**
     * 获取管理员仪表板核心统计数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:dashboard')")
    @GetMapping("/stats/core")
    public AjaxResult getCoreStats()
    {
        try {
            // 获取最近30天的统计数据
            Calendar cal = Calendar.getInstance();
            Date endDate = cal.getTime();
            cal.add(Calendar.DAY_OF_MONTH, -30);
            Date startDate = cal.getTime();
            
            Map<String, Object> stats = creditStatisticsService.getOverviewStats(startDate, endDate);
            return AjaxResult.success(stats);
        } catch (Exception e) {
            return AjaxResult.error("获取核心统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户画像数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:dashboard')")
    @GetMapping("/stats/userProfile")
    public AjaxResult getUserProfileStats()
    {
        try {
            Map<String, Object> profileStats = new HashMap<>();
            
            // 获取信用分分布
            List<Map<String, Object>> scoreDistribution = creditUserInfoMapper.getCreditScoreDistribution();
            profileStats.put("scoreDistribution", scoreDistribution);
            
            // 获取年龄分布
            List<Map<String, Object>> ageDistribution = creditUserInfoMapper.getAgeDistribution();
            profileStats.put("ageDistribution", ageDistribution);
            
            // 获取职业分布
            List<Map<String, Object>> occupationDistribution = creditUserInfoMapper.getOccupationDistribution();
            profileStats.put("occupationDistribution", occupationDistribution);
            
            // 获取地区分布
            List<Map<String, Object>> regionDistribution = creditUserInfoMapper.getRegionDistribution();
            profileStats.put("regionDistribution", regionDistribution);
            
            // 获取登录统计（用于计算活跃度）
            Calendar cal = Calendar.getInstance();
            Date endDate = cal.getTime();
            cal.add(Calendar.DAY_OF_MONTH, -30);
            Date startDate = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startDateStr = sdf.format(startDate);
            String endDateStr = sdf.format(endDate);
            
            List<Map<String, Object>> loginStats = creditUserInfoMapper.getLoginStatsByDateRange(startDateStr, endDateStr);
            profileStats.put("loginStats", loginStats);
            
            // 获取服务使用统计（用于计算服务使用得分）
            List<Map<String, Object>> serviceUsage = creditServiceConfigMapper.getServiceUsageStats(startDateStr, endDateStr);
            profileStats.put("serviceUsage", serviceUsage);
            
            // 构建收入分布数据（基于用户收入信息）
            List<Map<String, Object>> incomeDistribution = buildIncomeDistribution();
            profileStats.put("incomeDistribution", incomeDistribution);
            
            return AjaxResult.success(profileStats);
        } catch (Exception e) {
            return AjaxResult.error("获取用户画像数据失败：" + e.getMessage());
        }
    }

    /**
     * 构建收入分布数据
     */
    private List<Map<String, Object>> buildIncomeDistribution() {
        List<Map<String, Object>> incomeDistribution = new ArrayList<>();
        
        try {
            // 从用户信用信息中获取收入分布
            List<CreditUserInfo> userList = creditUserInfoService.selectCreditUserInfoList(new CreditUserInfo());
            
            int lowIncomeCount = 0;    // 低收入 (0-3000)
            int mediumIncomeCount = 0; // 中等收入 (3001-8000)
            int highIncomeCount = 0;   // 高收入 (8001+)
            
            for (CreditUserInfo user : userList) {
                if (user.getIncome() != null) {
                    double income = user.getIncome().doubleValue();
                    if (income <= 3000) {
                        lowIncomeCount++;
                    } else if (income <= 8000) {
                        mediumIncomeCount++;
                    } else {
                        highIncomeCount++;
                    }
                }
            }
            
            int totalCount = lowIncomeCount + mediumIncomeCount + highIncomeCount;
            
            if (totalCount > 0) {
                Map<String, Object> lowIncome = new HashMap<>();
                lowIncome.put("income_range", "低收入(0-3000)");
                lowIncome.put("count", lowIncomeCount);
                lowIncome.put("percentage", Math.round((double) lowIncomeCount / totalCount * 100 * 10.0) / 10.0);
                incomeDistribution.add(lowIncome);
                
                Map<String, Object> mediumIncome = new HashMap<>();
                mediumIncome.put("income_range", "中等收入(3001-8000)");
                mediumIncome.put("count", mediumIncomeCount);
                mediumIncome.put("percentage", Math.round((double) mediumIncomeCount / totalCount * 100 * 10.0) / 10.0);
                incomeDistribution.add(mediumIncome);
                
                Map<String, Object> highIncome = new HashMap<>();
                highIncome.put("income_range", "高收入(8001+)");
                highIncome.put("count", highIncomeCount);
                highIncome.put("percentage", Math.round((double) highIncomeCount / totalCount * 100 * 10.0) / 10.0);
                incomeDistribution.add(highIncome);
            } else {
                // 如果没有收入数据，设置默认分布
                Map<String, Object> defaultIncome = new HashMap<>();
                defaultIncome.put("income_range", "中等收入(3001-8000)");
                defaultIncome.put("count", 100);
                defaultIncome.put("percentage", 100.0);
                incomeDistribution.add(defaultIncome);
            }
        } catch (Exception e) {
            // 如果出现异常，设置默认分布
            Map<String, Object> defaultIncome = new HashMap<>();
            defaultIncome.put("income_range", "中等收入(3001-8000)");
            defaultIncome.put("count", 100);
            defaultIncome.put("percentage", 100.0);
            incomeDistribution.add(defaultIncome);
        }
        
        return incomeDistribution;
    }

    /**
     * 查询用户信用信息列表
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:list')")
    @GetMapping("/users/list")
    public TableDataInfo listUsers(CreditUserInfo creditUserInfo)
    {
        startPage();
        List<CreditUserInfo> list = creditUserInfoService.selectCreditUserInfoList(creditUserInfo);
        return getDataTable(list);
    }

    /**
     * 获取用户信用信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:query')")
    @GetMapping(value = "/users/{userId}")
    public AjaxResult getUserInfo(@PathVariable("userId") Long userId)
    {
        return success(creditUserInfoService.selectCreditUserInfoByUserId(userId));
    }

    /**
     * 新增用户信用信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:add')")
    @Log(title = "用户信用信息", businessType = BusinessType.INSERT)
    @PostMapping("/users")
    public AjaxResult addUser(@RequestBody CreditUserInfo creditUserInfo)
    {
        return toAjax(creditUserInfoService.insertCreditUserInfo(creditUserInfo));
    }

    /**
     * 创建用户和信用信息（同时创建系统用户和信用信息）
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:add')")
    @Log(title = "创建用户和信用信息", businessType = BusinessType.INSERT)
    @PostMapping("/users/createWithCredit")
    public AjaxResult createUserWithCredit(@RequestBody Map<String, Object> userData)
    {
        try {
            // 创建系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName((String) userData.get("userName"));
            sysUser.setNickName((String) userData.get("userName"));
            sysUser.setPhonenumber((String) userData.get("phonenumber"));
            sysUser.setEmail((String) userData.get("email"));
            sysUser.setSex((String) userData.get("sex"));
            
            // 密码加密处理
            String password = (String) userData.get("password");
            if (password != null && !password.isEmpty()) {
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
            } else {
                // 设置默认密码
                sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            }
            
            sysUser.setStatus("0"); // 正常状态
            sysUser.setDelFlag("0"); // 未删除
            sysUser.setCreateBy(SecurityUtils.getUsername());
            sysUser.setCreateTime(DateUtils.getNowDate());
            
            // 设置默认角色（普通用户角色）
            Long[] roleIds = {2L}; // 假设2是普通用户角色ID
            sysUser.setRoleIds(roleIds);
            
            // 保存系统用户
            int userResult = sysUserService.insertUser(sysUser);
            if (userResult <= 0) {
                return AjaxResult.error("创建系统用户失败");
            }
            
            // 创建信用信息
            CreditUserInfo creditUserInfo = new CreditUserInfo();
            creditUserInfo.setUserId(sysUser.getUserId());
            creditUserInfo.setUserName(sysUser.getUserName());
            creditUserInfo.setPhonenumber(sysUser.getPhonenumber());
            creditUserInfo.setIdCard((String) userData.get("idCard"));
            creditUserInfo.setEmail(sysUser.getEmail());
            creditUserInfo.setSex(sysUser.getSex());
            creditUserInfo.setAge((Integer) userData.get("age"));
            creditUserInfo.setOccupation((String) userData.get("occupation"));
            creditUserInfo.setIncome(new BigDecimal(userData.get("income").toString()));
            creditUserInfo.setProvince((String) userData.get("province"));
            creditUserInfo.setCity((String) userData.get("city"));
            creditUserInfo.setCreditScore((Integer) userData.get("creditScore"));
            creditUserInfo.setLifeServiceScore((Integer) userData.get("lifeServiceScore"));
            creditUserInfo.setBusinessScore((Integer) userData.get("businessScore"));
            creditUserInfo.setSocialScore((Integer) userData.get("socialScore"));
            creditUserInfo.setRemark((String) userData.get("remark"));
            creditUserInfo.setCreateBy(SecurityUtils.getUsername());
            creditUserInfo.setCreateTime(DateUtils.getNowDate());
            creditUserInfo.setLastUpdateTime(DateUtils.getNowDate());
            
            // 检查是否已存在信用信息记录
            CreditUserInfo existingInfo = creditUserInfoService.selectCreditUserInfoByUserId(sysUser.getUserId());
            int creditResult;
            if (existingInfo != null) {
                // 如果已存在，则更新
                creditUserInfo.setUpdateBy(SecurityUtils.getUsername());
                creditUserInfo.setUpdateTime(DateUtils.getNowDate());
                creditResult = creditUserInfoService.updateCreditUserInfo(creditUserInfo);
            } else {
                // 如果不存在，则插入
                creditResult = creditUserInfoService.insertCreditUserInfo(creditUserInfo);
            }
            
            if (creditResult <= 0) {
                // 如果信用信息操作失败，回滚系统用户
                sysUserService.deleteUserById(sysUser.getUserId());
                return AjaxResult.error("创建信用信息失败");
            }
            
            return AjaxResult.success("用户创建成功，默认密码为：123456");
        } catch (Exception e) {
            return AjaxResult.error("创建用户失败：" + e.getMessage());
        }
    }

    /**
     * 信用员创建用户（不需要管理员权限）
     */
    @Log(title = "信用员创建用户", businessType = BusinessType.INSERT)
    @PostMapping("/users/createByCreditStaff")
    public AjaxResult createUserByCreditStaff(@RequestBody Map<String, Object> userData)
    {
        try {
            // 创建系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName((String) userData.get("userName"));
            sysUser.setNickName((String) userData.get("userName"));
            sysUser.setPhonenumber((String) userData.get("phonenumber"));
            sysUser.setEmail((String) userData.get("email"));
            sysUser.setSex((String) userData.get("sex"));
            
            // 密码加密处理
            String password = (String) userData.get("password");
            if (password != null && !password.isEmpty()) {
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
            } else {
                // 设置默认密码
                sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            }
            
            sysUser.setStatus("0"); // 正常状态
            sysUser.setDelFlag("0"); // 未删除
            sysUser.setCreateBy(SecurityUtils.getUsername());
            sysUser.setCreateTime(DateUtils.getNowDate());
            
            // 设置默认角色（普通用户角色）
            Long[] roleIds = {2L}; // 假设2是普通用户角色ID
            sysUser.setRoleIds(roleIds);
            
            // 保存系统用户
            int userResult = sysUserService.insertUser(sysUser);
            if (userResult <= 0) {
                return AjaxResult.error("创建系统用户失败");
            }
            
            // 创建信用信息
            CreditUserInfo creditUserInfo = new CreditUserInfo();
            creditUserInfo.setUserId(sysUser.getUserId());
            creditUserInfo.setUserName(sysUser.getUserName());
            creditUserInfo.setPhonenumber(sysUser.getPhonenumber());
            creditUserInfo.setIdCard((String) userData.get("idCard"));
            creditUserInfo.setEmail(sysUser.getEmail());
            creditUserInfo.setSex(sysUser.getSex());
            
            // 处理年龄
            Object ageObj = userData.get("age");
            if (ageObj != null) {
                creditUserInfo.setAge((Integer) ageObj);
            }
            
            creditUserInfo.setOccupation((String) userData.get("occupation"));
            
            // 处理收入
            Object incomeObj = userData.get("income");
            if (incomeObj != null) {
                creditUserInfo.setIncome(new BigDecimal(incomeObj.toString()));
            } else {
                creditUserInfo.setIncome(new BigDecimal("5000"));
            }
            
            creditUserInfo.setProvince((String) userData.get("province"));
            creditUserInfo.setCity((String) userData.get("city"));
            
            // 处理信用分
            Object creditScoreObj = userData.get("creditScore");
            if (creditScoreObj != null) {
                creditUserInfo.setCreditScore((Integer) creditScoreObj);
            } else {
                creditUserInfo.setCreditScore(600);
            }
            
            // 处理其他分数
            Object lifeServiceScoreObj = userData.get("lifeServiceScore");
            if (lifeServiceScoreObj != null) {
                creditUserInfo.setLifeServiceScore((Integer) lifeServiceScoreObj);
            } else {
                creditUserInfo.setLifeServiceScore(200);
            }
            
            Object businessScoreObj = userData.get("businessScore");
            if (businessScoreObj != null) {
                creditUserInfo.setBusinessScore((Integer) businessScoreObj);
            } else {
                creditUserInfo.setBusinessScore(200);
            }
            
            Object socialScoreObj = userData.get("socialScore");
            if (socialScoreObj != null) {
                creditUserInfo.setSocialScore((Integer) socialScoreObj);
            } else {
                creditUserInfo.setSocialScore(200);
            }
            
            creditUserInfo.setRemark((String) userData.get("remark"));
            creditUserInfo.setCreateBy(SecurityUtils.getUsername());
            creditUserInfo.setCreateTime(DateUtils.getNowDate());
            creditUserInfo.setLastUpdateTime(DateUtils.getNowDate());
            
            // 检查是否已存在信用信息记录
            CreditUserInfo existingInfo = creditUserInfoService.selectCreditUserInfoByUserId(sysUser.getUserId());
            int creditResult;
            if (existingInfo != null) {
                // 如果已存在，则更新
                creditUserInfo.setUpdateBy(SecurityUtils.getUsername());
                creditUserInfo.setUpdateTime(DateUtils.getNowDate());
                creditResult = creditUserInfoService.updateCreditUserInfo(creditUserInfo);
            } else {
                // 如果不存在，则插入
                creditResult = creditUserInfoService.insertCreditUserInfo(creditUserInfo);
            }
            
            if (creditResult <= 0) {
                // 如果信用信息操作失败，回滚系统用户
                sysUserService.deleteUserById(sysUser.getUserId());
                return AjaxResult.error("创建信用信息失败");
            }
            
            return AjaxResult.success("用户创建成功，默认密码为：123456");
        } catch (Exception e) {
            logger.error("创建用户失败", e);
            return AjaxResult.error("创建用户失败：" + e.getMessage());
        }
    }

    /**
     * 信用员创建用户（完全开放，无需权限）
     */
    @Log(title = "信用员创建用户", businessType = BusinessType.INSERT)
    @PostMapping("/users/createOpen")
    public AjaxResult createUserOpen(@RequestBody Map<String, Object> userData)
    {
        try {
            // 创建系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName((String) userData.get("userName"));
            sysUser.setNickName((String) userData.get("userName"));
            sysUser.setPhonenumber((String) userData.get("phonenumber"));
            sysUser.setEmail((String) userData.get("email"));
            sysUser.setSex((String) userData.get("sex"));
            
            // 密码加密处理
            String password = (String) userData.get("password");
            if (password != null && !password.isEmpty()) {
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
            } else {
                // 设置默认密码
                sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            }
            
            sysUser.setStatus("0"); // 正常状态
            sysUser.setDelFlag("0"); // 未删除
            sysUser.setCreateBy(SecurityUtils.getUsername());
            sysUser.setCreateTime(DateUtils.getNowDate());
            
            // 设置默认角色（普通用户角色）
            Long[] roleIds = {2L}; // 假设2是普通用户角色ID
            sysUser.setRoleIds(roleIds);
            
            // 保存系统用户
            int userResult = sysUserService.insertUser(sysUser);
            if (userResult <= 0) {
                return AjaxResult.error("创建系统用户失败");
            }
            
            // 创建信用信息
            CreditUserInfo creditUserInfo = new CreditUserInfo();
            creditUserInfo.setUserId(sysUser.getUserId());
            creditUserInfo.setUserName(sysUser.getUserName());
            creditUserInfo.setPhonenumber(sysUser.getPhonenumber());
            creditUserInfo.setIdCard((String) userData.get("idCard"));
            creditUserInfo.setEmail(sysUser.getEmail());
            creditUserInfo.setSex(sysUser.getSex());
            
            // 处理年龄
            Object ageObj = userData.get("age");
            if (ageObj != null) {
                creditUserInfo.setAge((Integer) ageObj);
            }
            
            creditUserInfo.setOccupation((String) userData.get("occupation"));
            
            // 处理收入
            Object incomeObj = userData.get("income");
            if (incomeObj != null) {
                creditUserInfo.setIncome(new BigDecimal(incomeObj.toString()));
            } else {
                creditUserInfo.setIncome(new BigDecimal("5000"));
            }
            
            creditUserInfo.setProvince((String) userData.get("province"));
            creditUserInfo.setCity((String) userData.get("city"));
            
            // 处理信用分
            Object creditScoreObj = userData.get("creditScore");
            if (creditScoreObj != null) {
                creditUserInfo.setCreditScore((Integer) creditScoreObj);
            } else {
                creditUserInfo.setCreditScore(600);
            }
            
            // 处理其他分数
            Object lifeServiceScoreObj = userData.get("lifeServiceScore");
            if (lifeServiceScoreObj != null) {
                creditUserInfo.setLifeServiceScore((Integer) lifeServiceScoreObj);
            } else {
                creditUserInfo.setLifeServiceScore(200);
            }
            
            Object businessScoreObj = userData.get("businessScore");
            if (businessScoreObj != null) {
                creditUserInfo.setBusinessScore((Integer) businessScoreObj);
            } else {
                creditUserInfo.setBusinessScore(200);
            }
            
            Object socialScoreObj = userData.get("socialScore");
            if (socialScoreObj != null) {
                creditUserInfo.setSocialScore((Integer) socialScoreObj);
            } else {
                creditUserInfo.setSocialScore(200);
            }
            
            creditUserInfo.setRemark((String) userData.get("remark"));
            creditUserInfo.setCreateBy(SecurityUtils.getUsername());
            creditUserInfo.setCreateTime(DateUtils.getNowDate());
            creditUserInfo.setLastUpdateTime(DateUtils.getNowDate());
            
            // 检查是否已存在信用信息记录
            CreditUserInfo existingInfo = creditUserInfoService.selectCreditUserInfoByUserId(sysUser.getUserId());
            int creditResult;
            if (existingInfo != null) {
                // 如果已存在，则更新
                creditUserInfo.setUpdateBy(SecurityUtils.getUsername());
                creditUserInfo.setUpdateTime(DateUtils.getNowDate());
                creditResult = creditUserInfoService.updateCreditUserInfo(creditUserInfo);
            } else {
                // 如果不存在，则插入
                creditResult = creditUserInfoService.insertCreditUserInfo(creditUserInfo);
            }
            
            if (creditResult <= 0) {
                // 如果信用信息操作失败，回滚系统用户
                sysUserService.deleteUserById(sysUser.getUserId());
                return AjaxResult.error("创建信用信息失败");
            }
            
            return AjaxResult.success("用户创建成功，默认密码为：123456");
        } catch (Exception e) {
            logger.error("创建用户失败", e);
            return AjaxResult.error("创建用户失败：" + e.getMessage());
        }
    }

    /**
     * 修改用户信用信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:edit')")
    @Log(title = "用户信用信息", businessType = BusinessType.UPDATE)
    @PutMapping("/users")
    public AjaxResult editUser(@RequestBody CreditUserInfo creditUserInfo)
    {
        return toAjax(creditUserInfoService.updateCreditUserInfo(creditUserInfo));
    }

    /**
     * 删除用户信用信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:remove')")
    @Log(title = "用户信用信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/users/{userIds}")
    public AjaxResult removeUsers(@PathVariable Long[] userIds)
    {
        return toAjax(creditUserInfoService.deleteCreditUserInfoByUserIds(userIds));
    }

    /**
     * 导出用户数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:export')")
    @Log(title = "用户数据导出", businessType = BusinessType.EXPORT)
    @PostMapping("/users/export")
    public void exportUsers(HttpServletResponse response, CreditUserInfo creditUserInfo)
    {
        List<CreditUserInfo> list = creditUserInfoService.selectCreditUserInfoList(creditUserInfo);
        ExcelUtil<CreditUserInfo> util = new ExcelUtil<CreditUserInfo>(CreditUserInfo.class);
        util.exportExcel(response, list, "用户信用信息数据");
    }

    /**
     * 获取详细统计数据
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:statistics')")
    @GetMapping("/statistics/detailed")
    public AjaxResult getDetailedStats(@RequestParam(required = false) String dateRange)
    {
        try {
            // 解析日期范围
            Calendar cal = Calendar.getInstance();
            Date endDate = cal.getTime();
            Date startDate;
            
            if (dateRange != null && !dateRange.isEmpty()) {
                String[] dates = dateRange.split(",");
                if (dates.length >= 2) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    startDate = sdf.parse(dates[0]);
                    endDate = sdf.parse(dates[1]);
                } else {
                    cal.add(Calendar.DAY_OF_MONTH, -30);
                    startDate = cal.getTime();
                }
            } else {
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> stats = creditStatisticsService.getDetailedStats(startDate, endDate);
            return AjaxResult.success(stats);
        } catch (Exception e) {
            return AjaxResult.error("获取详细统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 调整用户信用分
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:edit')")
    @Log(title = "调整用户信用分", businessType = BusinessType.UPDATE)
    @PostMapping("/users/adjustScore")
    public AjaxResult adjustUserScore(@RequestBody Map<String, Object> params)
    {
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            Integer scoreChange = Integer.valueOf(params.get("scoreChange").toString());
            String reason = params.get("reason").toString();
            
            CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            if (userInfo == null) {
                return AjaxResult.error("用户不存在");
            }
            
            // 记录原分数
            Integer oldScore = userInfo.getCreditScore();
            
            // 调整信用分
            Integer newScore = userInfo.getCreditScore() + scoreChange;
            if (newScore < 0) newScore = 0;
            if (newScore > 1000) newScore = 1000;
            
            userInfo.setCreditScore(newScore);
            userInfo.setLastUpdateTime(DateUtils.getNowDate());
            
            int result = creditUserInfoService.updateCreditUserInfo(userInfo);
            
            if (result > 0) {
                // 记录信用分变更历史
                try {
                    CreditScoreHistory history = new CreditScoreHistory();
                    history.setUserId(userId);
                    history.setUserName(userInfo.getUserName());
                    history.setPhonenumber(userInfo.getPhonenumber());
                    history.setOldScore(oldScore);
                    history.setNewScore(newScore);
                    history.setChangeAmount(scoreChange);
                    history.setReason(reason);
                    history.setOperator(SecurityUtils.getUsername());
                    history.setChangeType(scoreChange > 0 ? "increase" : (scoreChange < 0 ? "decrease" : "no_change"));
                    history.setCreateTime(DateUtils.getNowDate());
                    
                    creditScoreHistoryMapper.insertCreditScoreHistory(history);
                } catch (Exception e) {
                    // 历史记录失败不影响主流程
                    logger.warn("记录信用分变更历史失败：" + e.getMessage());
                }
                
                return AjaxResult.success("信用分调整成功");
            } else {
                return AjaxResult.error("信用分调整失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("调整信用分失败：" + e.getMessage());
        }
    }

    /**
     * 批量调整用户信用分
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:edit')")
    @Log(title = "批量调整用户信用分", businessType = BusinessType.UPDATE)
    @PostMapping("/users/batchAdjustScore")
    public AjaxResult batchAdjustUserScore(@RequestBody Map<String, Object> params)
    {
        try {
            @SuppressWarnings("unchecked")
            List<Long> userIds = (List<Long>) params.get("userIds");
            String adjustType = (String) params.get("adjustType");
            Integer scoreValue = Integer.valueOf(params.get("scoreValue").toString());
            String reason = (String) params.get("reason");
            
            if (userIds == null || userIds.isEmpty()) {
                return AjaxResult.error("请选择要调整的用户");
            }
            
            if (scoreValue == null || scoreValue <= 0) {
                return AjaxResult.error("调整分数必须大于0");
            }
            
            if (reason == null || reason.trim().isEmpty()) {
                return AjaxResult.error("调整原因不能为空");
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (Long userId : userIds) {
                try {
                    CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
                    if (userInfo == null) {
                        failCount++;
                        continue;
                    }
                    
                    // 根据调整类型计算新分数
                    Integer newScore = userInfo.getCreditScore();
                    if ("add".equals(adjustType)) {
                        newScore = userInfo.getCreditScore() + scoreValue;
                    } else if ("subtract".equals(adjustType)) {
                        newScore = userInfo.getCreditScore() - scoreValue;
                    } else if ("set".equals(adjustType)) {
                        newScore = scoreValue;
                    }
                    
                    // 确保分数在有效范围内
                        if (newScore < 0) newScore = 0;
                        if (newScore > 1000) newScore = 1000;
                        
                        userInfo.setCreditScore(newScore);
                        userInfo.setLastUpdateTime(DateUtils.getNowDate());
                        
                    int result = creditUserInfoService.updateCreditUserInfo(userInfo);
                    if (result > 0) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("message", String.format("批量调整完成：成功%d个，失败%d个", successCount, failCount));
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("批量调整信用分失败：" + e.getMessage());
        }
    }

    /**
     * 切换用户状态
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:edit')")
    @Log(title = "切换用户状态", businessType = BusinessType.UPDATE)
    @PostMapping("/users/toggleStatus")
    public AjaxResult toggleUserStatus(@RequestBody Map<String, Object> params)
    {
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            String status = params.get("status").toString();
            
            // 更新系统用户状态
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setStatus(status);
            sysUser.setUpdateBy(SecurityUtils.getUsername());
            sysUser.setUpdateTime(DateUtils.getNowDate());
            
            int result = sysUserService.updateUser(sysUser);
            return toAjax(result);
        } catch (Exception e) {
            return AjaxResult.error("切换用户状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信用分变更历史
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:query')")
    @GetMapping("/users/{userId}/scoreHistory")
    public AjaxResult getUserScoreHistory(@PathVariable("userId") Long userId)
    {
        try {
            // 查询真实的信用分变更历史
            List<CreditScoreHistory> historyList = creditScoreHistoryMapper.selectCreditScoreHistoryByUserId(userId);
            
            // 如果没有历史记录，返回空列表
            if (historyList == null) {
                historyList = new ArrayList<>();
            }
            
            return AjaxResult.success(historyList);
        } catch (Exception e) {
            return AjaxResult.error("获取信用分变更历史失败：" + e.getMessage());
        }
    }

    /**
     * 发送用户通知
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:edit')")
    @Log(title = "发送用户通知", businessType = BusinessType.OTHER)
    @PostMapping("/users/sendNotification")
    public AjaxResult sendUserNotification(@RequestBody Map<String, Object> params)
    {
        try {
            List<Long> userIds = (List<Long>) params.get("userIds");
            String title = (String) params.get("title");
            String content = (String) params.get("content");
            String type = (String) params.get("type");
            
            if (userIds == null || userIds.isEmpty()) {
                return AjaxResult.error("请选择要通知的用户");
            }
            
            if (title == null || title.trim().isEmpty()) {
                return AjaxResult.error("通知标题不能为空");
            }
            
            if (content == null || content.trim().isEmpty()) {
                return AjaxResult.error("通知内容不能为空");
            }
            
            // 这里应该实现实际的通知发送逻辑
            // 可以发送短信、邮件、站内信等
            // 暂时返回成功
            Map<String, Object> result = new HashMap<>();
            result.put("successCount", userIds.size());
            result.put("failCount", 0);
            result.put("message", "通知发送成功");
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("发送用户通知失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户统计信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:users:query')")
    @GetMapping("/users/statistics")
    public AjaxResult getUserStatistics()
    {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 总用户数
            int totalUsers = creditUserInfoMapper.selectCreditUserInfoCount();
            stats.put("totalUsers", totalUsers);
            
            // 活跃用户数（最近30天有登录记录的用户）
            Calendar cal = Calendar.getInstance();
            Date endDate = cal.getTime();
            cal.add(Calendar.DAY_OF_MONTH, -30);
            Date startDate = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startDateStr = sdf.format(startDate);
            String endDateStr = sdf.format(endDate);
            
            int activeUsers = creditUserInfoMapper.getActiveUsersCount(startDateStr, endDateStr);
            stats.put("activeUsers", activeUsers);
            
            // 平均信用分
            Double avgCreditScore = creditUserInfoMapper.getAverageCreditScore();
            stats.put("avgCreditScore", avgCreditScore != null ? Math.round(avgCreditScore) : 0);
            
            // 信用分分布
            List<Map<String, Object>> scoreDistribution = creditUserInfoMapper.getCreditScoreDistribution();
            stats.put("scoreDistribution", scoreDistribution);
            
            // 地区分布
            List<Map<String, Object>> regionDistribution = creditUserInfoMapper.getRegionDistribution();
            stats.put("regionDistribution", regionDistribution);
            
            // 年龄分布
            List<Map<String, Object>> ageDistribution = creditUserInfoMapper.getAgeDistribution();
            stats.put("ageDistribution", ageDistribution);
            
            // 职业分布
            List<Map<String, Object>> occupationDistribution = creditUserInfoMapper.getOccupationDistribution();
            stats.put("occupationDistribution", occupationDistribution);
            
            return AjaxResult.success(stats);
        } catch (Exception e) {
            return AjaxResult.error("获取用户统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 信用员查询用户详情（无需权限）
     */
    @GetMapping("/users/detail/{userId}")
    public AjaxResult getUserDetail(@PathVariable("userId") Long userId)
    {
        try {
            CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            if (userInfo == null) {
                return AjaxResult.error("用户不存在");
            }
            return AjaxResult.success(userInfo);
        } catch (Exception e) {
            logger.error("查询用户详情失败", e);
            return AjaxResult.error("查询用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 信用员更新用户信息（无需权限）
     */
    @Log(title = "信用员更新用户", businessType = BusinessType.UPDATE)
    @PutMapping("/users/updateOpen")
    public AjaxResult updateUserOpen(@RequestBody CreditUserInfo creditUserInfo)
    {
        try {
            creditUserInfo.setUpdateBy(SecurityUtils.getUsername());
            creditUserInfo.setUpdateTime(DateUtils.getNowDate());
            creditUserInfo.setLastUpdateTime(DateUtils.getNowDate());
            
            int result = creditUserInfoService.updateCreditUserInfo(creditUserInfo);
            if (result > 0) {
                return AjaxResult.success("用户信息更新成功");
            } else {
                return AjaxResult.error("用户信息更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
            return AjaxResult.error("更新用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 信用员删除用户（无需权限）
     */
    @Log(title = "信用员删除用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/users/deleteOpen/{userIds}")
    public AjaxResult deleteUsersOpen(@PathVariable Long[] userIds)
    {
        try {
            int result = creditUserInfoService.deleteCreditUserInfoByUserIds(userIds);
            if (result > 0) {
                // 同时删除系统用户
                for (Long userId : userIds) {
                    try {
                        sysUserService.deleteUserById(userId);
                    } catch (Exception e) {
                        logger.warn("删除系统用户失败，用户ID：" + userId, e);
                    }
                }
                return AjaxResult.success("用户删除成功");
            } else {
                return AjaxResult.error("用户删除失败");
            }
        } catch (Exception e) {
            logger.error("删除用户失败", e);
            return AjaxResult.error("删除用户失败：" + e.getMessage());
        }
    }

    // ======================== 新闻管理功能 ========================

    /**
     * 查询新闻列表（管理员）
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:list')")
    @GetMapping("/news/list")
    public TableDataInfo listNews(CreditNews creditNews)
    {
        startPage();
        List<CreditNews> list = creditNewsService.selectCreditNewsList(creditNews);
        return getDataTable(list);
    }

    /**
     * 获取新闻详细信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:query')")
    @GetMapping("/news/{newsId}")
    public AjaxResult getNewsInfo(@PathVariable("newsId") Long newsId)
    {
        return success(creditNewsService.selectCreditNewsByNewsId(newsId));
    }

    /**
     * 新增新闻
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:add')")
    @Log(title = "新闻管理", businessType = BusinessType.INSERT)
    @PostMapping("/news")
    public AjaxResult addNews(@RequestBody CreditNews creditNews)
    {
        return toAjax(creditNewsService.insertCreditNews(creditNews));
    }

    /**
     * 修改新闻
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:edit')")
    @Log(title = "新闻管理", businessType = BusinessType.UPDATE)
    @PutMapping("/news")
    public AjaxResult editNews(@RequestBody CreditNews creditNews)
    {
        return toAjax(creditNewsService.updateCreditNews(creditNews));
    }

    /**
     * 删除新闻
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:remove')")
    @Log(title = "新闻管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/news/{newsIds}")
    public AjaxResult removeNews(@PathVariable Long[] newsIds)
    {
        return toAjax(creditNewsService.deleteCreditNewsByNewsIds(newsIds));
    }

    /**
     * 批量发布新闻
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:edit')")
    @Log(title = "批量发布新闻", businessType = BusinessType.UPDATE)
    @PostMapping("/news/batchPublish")
    public AjaxResult batchPublishNews(@RequestBody Map<String, Object> params)
    {
        try {
            @SuppressWarnings("unchecked")
            List<Long> newsIds = (List<Long>) params.get("newsIds");
            Integer publishStatus = Integer.valueOf(params.get("publishStatus").toString());
            
            int successCount = 0;
            for (Long newsId : newsIds) {
                try {
                    CreditNews news = creditNewsService.selectCreditNewsByNewsId(newsId);
                    if (news != null) {
                        news.setPublishStatus(publishStatus);
                        creditNewsService.updateCreditNews(news);
                        successCount++;
                    }
                } catch (Exception e) {
                    continue;
                }
            }
            
            return AjaxResult.success("成功" + (publishStatus == 1 ? "发布" : "取消发布") + " " + successCount + " 条新闻");
        } catch (Exception e) {
            return AjaxResult.error("批量操作失败：" + e.getMessage());
        }
    }

    /**
     * 设置新闻置顶状态
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:edit')")
    @Log(title = "设置新闻置顶", businessType = BusinessType.UPDATE)
    @PostMapping("/news/setTop")
    public AjaxResult setNewsTop(@RequestBody Map<String, Object> params)
    {
        try {
            Long newsId = Long.valueOf(params.get("newsId").toString());
            Integer isTop = Integer.valueOf(params.get("isTop").toString());
            
            CreditNews news = creditNewsService.selectCreditNewsByNewsId(newsId);
            if (news == null) {
                return AjaxResult.error("新闻不存在");
            }
            
            news.setIsTop(isTop);
            return toAjax(creditNewsService.updateCreditNews(news));
        } catch (Exception e) {
            return AjaxResult.error("设置置顶失败：" + e.getMessage());
        }
    }

    /**
     * 导出新闻列表
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:export')")
    @Log(title = "新闻导出", businessType = BusinessType.EXPORT)
    @PostMapping("/news/export")
    public void exportNews(HttpServletResponse response, CreditNews creditNews)
    {
        List<CreditNews> list = creditNewsService.selectCreditNewsList(creditNews);
        ExcelUtil<CreditNews> util = new ExcelUtil<CreditNews>(CreditNews.class);
        util.exportExcel(response, list, "新闻资讯数据");
    }

    /**
     * 获取新闻统计信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:news:query')")
    @GetMapping("/news/statistics")
    public AjaxResult getNewsStatistics()
    {
        try {
            Map<String, Object> stats = creditNewsService.getNewsStats();
            return AjaxResult.success(stats);
        } catch (Exception e) {
            return AjaxResult.error("获取新闻统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 信用员查询新闻列表（无需权限）
     */
    @GetMapping("/news/listOpen")
    public TableDataInfo listNewsOpen(CreditNews creditNews)
    {
        startPage();
        List<CreditNews> list = creditNewsService.selectCreditNewsList(creditNews);
        return getDataTable(list);
    }

    /**
     * 信用员获取新闻详细信息（无需权限）
     */
    @GetMapping("/news/detail/{newsId}")
    public AjaxResult getNewsDetail(@PathVariable("newsId") Long newsId)
    {
        try {
            CreditNews news = creditNewsService.selectCreditNewsByNewsId(newsId);
            if (news == null) {
                return AjaxResult.error("新闻不存在");
            }
            return AjaxResult.success(news);
        } catch (Exception e) {
            logger.error("查询新闻详情失败", e);
            return AjaxResult.error("查询新闻详情失败：" + e.getMessage());
        }
    }

    /**
     * 信用员新增新闻（无需权限）
     */
    @Log(title = "信用员新增新闻", businessType = BusinessType.INSERT)
    @PostMapping("/news/addOpen")
    public AjaxResult addNewsOpen(@RequestBody CreditNews creditNews)
    {
        try {
            creditNews.setCreateBy(SecurityUtils.getUsername());
            creditNews.setCreateTime(DateUtils.getNowDate());
            int result = creditNewsService.insertCreditNews(creditNews);
            if (result > 0) {
                return AjaxResult.success("新闻新增成功");
            } else {
                return AjaxResult.error("新闻新增失败");
            }
        } catch (Exception e) {
            logger.error("新增新闻失败", e);
            return AjaxResult.error("新增新闻失败：" + e.getMessage());
        }
    }

    /**
     * 信用员修改新闻（无需权限）
     */
    @Log(title = "信用员修改新闻", businessType = BusinessType.UPDATE)
    @PutMapping("/news/editOpen")
    public AjaxResult editNewsOpen(@RequestBody CreditNews creditNews)
    {
        try {
            creditNews.setUpdateBy(SecurityUtils.getUsername());
            creditNews.setUpdateTime(DateUtils.getNowDate());
            int result = creditNewsService.updateCreditNews(creditNews);
            if (result > 0) {
                return AjaxResult.success("新闻修改成功");
            } else {
                return AjaxResult.error("新闻修改失败");
            }
        } catch (Exception e) {
            logger.error("修改新闻失败", e);
            return AjaxResult.error("修改新闻失败：" + e.getMessage());
        }
    }

    /**
     * 信用员删除新闻（无需权限）
     */
    @Log(title = "信用员删除新闻", businessType = BusinessType.DELETE)
    @DeleteMapping("/news/deleteOpen/{newsIds}")
    public AjaxResult removeNewsOpen(@PathVariable Long[] newsIds)
    {
        try {
            int result = creditNewsService.deleteCreditNewsByNewsIds(newsIds);
            if (result > 0) {
                return AjaxResult.success("新闻删除成功");
            } else {
                return AjaxResult.error("新闻删除失败");
            }
        } catch (Exception e) {
            logger.error("删除新闻失败", e);
            return AjaxResult.error("删除新闻失败：" + e.getMessage());
        }
    }

    /**
     * 信用员批量发布新闻（无需权限）
     */
    @Log(title = "信用员批量发布新闻", businessType = BusinessType.UPDATE)
    @PostMapping("/news/batchPublishOpen")
    public AjaxResult batchPublishNewsOpen(@RequestBody Map<String, Object> params)
    {
        try {
            @SuppressWarnings("unchecked")
            List<Long> newsIds = (List<Long>) params.get("newsIds");
            Integer publishStatus = Integer.valueOf(params.get("publishStatus").toString());
            
            int successCount = 0;
            for (Long newsId : newsIds) {
                try {
                    CreditNews news = creditNewsService.selectCreditNewsByNewsId(newsId);
                    if (news != null) {
                        news.setPublishStatus(publishStatus);
                        news.setUpdateBy(SecurityUtils.getUsername());
                        news.setUpdateTime(DateUtils.getNowDate());
                        creditNewsService.updateCreditNews(news);
                        successCount++;
                    }
                } catch (Exception e) {
                    continue;
                }
            }
            
            return AjaxResult.success("成功" + (publishStatus == 1 ? "发布" : "取消发布") + " " + successCount + " 条新闻");
        } catch (Exception e) {
            return AjaxResult.error("批量操作失败：" + e.getMessage());
        }
    }

    /**
     * 信用员设置新闻置顶状态（无需权限）
     */
    @Log(title = "信用员设置新闻置顶", businessType = BusinessType.UPDATE)
    @PostMapping("/news/setTopOpen")
    public AjaxResult setNewsTopOpen(@RequestBody Map<String, Object> params)
    {
        try {
            Long newsId = Long.valueOf(params.get("newsId").toString());
            Integer isTop = Integer.valueOf(params.get("isTop").toString());
            
            CreditNews news = creditNewsService.selectCreditNewsByNewsId(newsId);
            if (news == null) {
                return AjaxResult.error("新闻不存在");
            }
            
            news.setIsTop(isTop);
            news.setUpdateBy(SecurityUtils.getUsername());
            news.setUpdateTime(DateUtils.getNowDate());
            
            int result = creditNewsService.updateCreditNews(news);
            if (result > 0) {
                return AjaxResult.success("设置" + (isTop == 1 ? "置顶" : "取消置顶") + "成功");
            } else {
                return AjaxResult.error("设置失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("设置失败：" + e.getMessage());
        }
    }

    // ======================== 服务配置管理功能 ========================

    /**
     * 查询服务配置列表
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:list')")
    @GetMapping("/services/list")
    public TableDataInfo listServices(CreditServiceConfig creditServiceConfig)
    {
        startPage();
        List<CreditServiceConfig> list = creditServiceConfigService.selectCreditServiceConfigList(creditServiceConfig);
        return getDataTable(list);
    }

    /**
     * 获取服务配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:query')")
    @GetMapping("/services/{configId}")
    public AjaxResult getServiceInfo(@PathVariable("configId") Long configId)
    {
        return success(creditServiceConfigService.selectCreditServiceConfigByConfigId(configId));
    }

    /**
     * 新增服务配置
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:add')")
    @Log(title = "服务配置管理", businessType = BusinessType.INSERT)
    @PostMapping("/services")
    public AjaxResult addService(@RequestBody CreditServiceConfig creditServiceConfig)
    {
        return toAjax(creditServiceConfigService.insertCreditServiceConfig(creditServiceConfig));
    }

    /**
     * 修改服务配置
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:edit')")
    @Log(title = "服务配置管理", businessType = BusinessType.UPDATE)
    @PutMapping("/services")
    public AjaxResult editService(@RequestBody CreditServiceConfig creditServiceConfig)
    {
        return toAjax(creditServiceConfigService.updateCreditServiceConfig(creditServiceConfig));
    }

    /**
     * 删除服务配置
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:remove')")
    @Log(title = "服务配置管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/services/{configIds}")
    public AjaxResult removeServices(@PathVariable Long[] configIds)
    {
        return toAjax(creditServiceConfigService.deleteCreditServiceConfigByConfigIds(configIds));
    }

    /**
     * 批量启用/禁用服务
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:edit')")
    @Log(title = "批量操作服务状态", businessType = BusinessType.UPDATE)
    @PostMapping("/services/batchStatus")
    public AjaxResult batchUpdateServiceStatus(@RequestBody Map<String, Object> params)
    {
        try {
            @SuppressWarnings("unchecked")
            List<Long> configIds = (List<Long>) params.get("configIds");
            String status = params.get("status").toString();
            
            int successCount = 0;
            for (Long configId : configIds) {
                try {
                    CreditServiceConfig config = creditServiceConfigService.selectCreditServiceConfigByConfigId(configId);
                    if (config != null) {
                        config.setStatus(status);
                        creditServiceConfigService.updateCreditServiceConfig(config);
                        successCount++;
                    }
                } catch (Exception e) {
                    continue;
                }
            }
            
            return AjaxResult.success("成功" + (status.equals("1") ? "启用" : "禁用") + " " + successCount + " 个服务");
        } catch (Exception e) {
            return AjaxResult.error("批量操作失败：" + e.getMessage());
        }
    }

    /**
     * 导出服务配置列表
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:export')")
    @Log(title = "服务配置导出", businessType = BusinessType.EXPORT)
    @PostMapping("/services/export")
    public void exportServices(HttpServletResponse response, CreditServiceConfig creditServiceConfig)
    {
        List<CreditServiceConfig> list = creditServiceConfigService.selectCreditServiceConfigList(creditServiceConfig);
        ExcelUtil<CreditServiceConfig> util = new ExcelUtil<CreditServiceConfig>(CreditServiceConfig.class);
        util.exportExcel(response, list, "服务配置数据");
    }

    /**
     * 获取服务使用统计
     */
    @PreAuthorize("@ss.hasPermi('credit:admin:services:query')")
    @GetMapping("/services/usageStats")
    public AjaxResult getServiceUsageStats()
    {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 获取当前日期范围（最近30天）
            Calendar cal = Calendar.getInstance();
            Date endDate = cal.getTime();
            cal.add(Calendar.DAY_OF_MONTH, -30);
            Date startDate = cal.getTime();
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startDateStr = sdf.format(startDate);
            String endDateStr = sdf.format(endDate);
            
            // 获取各类型服务的使用统计
            List<Map<String, Object>> serviceUsage = creditServiceConfigMapper.getServiceUsageStats(startDateStr, endDateStr);
            stats.put("serviceUsage", serviceUsage);
            
            // 获取服务类型分布
            List<Map<String, Object>> serviceTypeDistribution = creditServiceConfigMapper.getServiceTypeDistribution();
            stats.put("serviceTypeDistribution", serviceTypeDistribution);
            
            return AjaxResult.success(stats);
        } catch (Exception e) {
            return AjaxResult.error("获取服务使用统计失败：" + e.getMessage());
        }
    }

    // ======================== 信用员服务配置管理功能（无需权限） ========================

    /**
     * 信用员查询服务配置列表（无需权限）
     */
    @GetMapping("/services/listOpen")
    public TableDataInfo listServicesOpen(CreditServiceConfig creditServiceConfig)
    {
        startPage();
        List<CreditServiceConfig> list = creditServiceConfigService.selectCreditServiceConfigList(creditServiceConfig);
        return getDataTable(list);
    }

    /**
     * 信用员获取服务配置详细信息（无需权限）
     */
    @GetMapping("/services/detail/{configId}")
    public AjaxResult getServiceDetailOpen(@PathVariable("configId") Long configId)
    {
        try {
            CreditServiceConfig service = creditServiceConfigService.selectCreditServiceConfigByConfigId(configId);
            if (service == null) {
                return AjaxResult.error("服务配置不存在");
            }
            return AjaxResult.success(service);
        } catch (Exception e) {
            logger.error("获取服务配置详情失败", e);
            return AjaxResult.error("获取服务配置详情失败：" + e.getMessage());
        }
    }

    /**
     * 信用员新增服务配置（无需权限）
     */
    @Log(title = "信用员新增服务配置", businessType = BusinessType.INSERT)
    @PostMapping("/services/addOpen")
    public AjaxResult addServiceOpen(@RequestBody CreditServiceConfig creditServiceConfig)
    {
        try {
            creditServiceConfig.setCreateBy(SecurityUtils.getUsername());
            creditServiceConfig.setCreateTime(DateUtils.getNowDate());
            int result = creditServiceConfigService.insertCreditServiceConfig(creditServiceConfig);
            if (result > 0) {
                return AjaxResult.success("服务配置新增成功");
            } else {
                return AjaxResult.error("服务配置新增失败");
            }
        } catch (Exception e) {
            logger.error("新增服务配置失败", e);
            return AjaxResult.error("新增服务配置失败：" + e.getMessage());
        }
    }

    /**
     * 信用员修改服务配置（无需权限）
     */
    @Log(title = "信用员修改服务配置", businessType = BusinessType.UPDATE)
    @PutMapping("/services/editOpen")
    public AjaxResult editServiceOpen(@RequestBody CreditServiceConfig creditServiceConfig)
    {
        try {
            creditServiceConfig.setUpdateBy(SecurityUtils.getUsername());
            creditServiceConfig.setUpdateTime(DateUtils.getNowDate());
            int result = creditServiceConfigService.updateCreditServiceConfig(creditServiceConfig);
            if (result > 0) {
                return AjaxResult.success("服务配置修改成功");
            } else {
                return AjaxResult.error("服务配置修改失败");
            }
        } catch (Exception e) {
            logger.error("修改服务配置失败", e);
            return AjaxResult.error("修改服务配置失败：" + e.getMessage());
        }
    }

    /**
     * 信用员删除服务配置（无需权限）
     */
    @Log(title = "信用员删除服务配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/services/deleteOpen/{configIds}")
    public AjaxResult removeServicesOpen(@PathVariable Long[] configIds)
    {
        try {
            int result = creditServiceConfigService.deleteCreditServiceConfigByConfigIds(configIds);
            if (result > 0) {
                return AjaxResult.success("服务配置删除成功");
            } else {
                return AjaxResult.error("服务配置删除失败");
            }
        } catch (Exception e) {
            logger.error("删除服务配置失败", e);
            return AjaxResult.error("删除服务配置失败：" + e.getMessage());
        }
    }

    /**
     * 信用员批量更新服务状态（无需权限）
     */
    @Log(title = "信用员批量操作服务状态", businessType = BusinessType.UPDATE)
    @PostMapping("/services/batchStatusOpen")
    public AjaxResult batchUpdateServiceStatusOpen(@RequestBody Map<String, Object> params)
    {
        try {
            List<Long> configIds = (List<Long>) params.get("configIds");
            String status = (String) params.get("status");
            
            if (configIds == null || configIds.isEmpty()) {
                return AjaxResult.error("请选择要操作的服务配置");
            }
            
            int result = 0;
            for (Long configId : configIds) {
                CreditServiceConfig config = new CreditServiceConfig();
                config.setConfigId(configId);
                config.setStatus(status);
                config.setUpdateBy(SecurityUtils.getUsername());
                config.setUpdateTime(DateUtils.getNowDate());
                result += creditServiceConfigService.updateCreditServiceConfig(config);
            }
            
            return toAjax(result);
        } catch (Exception e) {
            return AjaxResult.error("批量更新服务状态失败：" + e.getMessage());
        }
    }

    // ======================== 信用员统计接口（无需权限） ========================

    /**
     * 获取核心统计数据（无需权限）
     */
    @GetMapping("/stats/coreOpen")
    public AjaxResult getCoreStatsOpen()
    {
        try {
            // 获取最近30天的统计数据
            Calendar cal = Calendar.getInstance();
            Date endDate = cal.getTime();
            cal.add(Calendar.DAY_OF_MONTH, -30);
            Date startDate = cal.getTime();
            
            Map<String, Object> stats = creditStatisticsService.getOverviewStats(startDate, endDate);
            return AjaxResult.success(stats);
        } catch (Exception e) {
            return AjaxResult.error("获取核心统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户画像数据（无需权限）
     */
    @GetMapping("/stats/userProfileOpen")
    public AjaxResult getUserProfileStatsOpen()
    {
        try {
            Map<String, Object> profileStats = new HashMap<>();
            
            // 获取信用分分布
            List<Map<String, Object>> scoreDistribution = creditUserInfoMapper.getCreditScoreDistribution();
            profileStats.put("scoreDistribution", scoreDistribution);
            
            // 获取年龄分布
            List<Map<String, Object>> ageDistribution = creditUserInfoMapper.getAgeDistribution();
            profileStats.put("ageDistribution", ageDistribution);
            
            // 获取职业分布
            List<Map<String, Object>> occupationDistribution = creditUserInfoMapper.getOccupationDistribution();
            profileStats.put("occupationDistribution", occupationDistribution);
            
            // 获取地区分布
            List<Map<String, Object>> regionDistribution = creditUserInfoMapper.getRegionDistribution();
            profileStats.put("regionDistribution", regionDistribution);
            
            // 获取登录统计（用于计算活跃度）
            Calendar cal = Calendar.getInstance();
            Date endDate = cal.getTime();
            cal.add(Calendar.DAY_OF_MONTH, -30);
            Date startDate = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startDateStr = sdf.format(startDate);
            String endDateStr = sdf.format(endDate);
            
            List<Map<String, Object>> loginStats = creditUserInfoMapper.getLoginStatsByDateRange(startDateStr, endDateStr);
            profileStats.put("loginStats", loginStats);
            
            // 获取服务使用统计（用于计算服务使用得分）
            List<Map<String, Object>> serviceUsage = creditServiceConfigMapper.getServiceUsageStats(startDateStr, endDateStr);
            profileStats.put("serviceUsage", serviceUsage);
            
            // 构建收入分布数据（基于用户收入信息）
            List<Map<String, Object>> incomeDistribution = buildIncomeDistribution();
            profileStats.put("incomeDistribution", incomeDistribution);
            
            return AjaxResult.success(profileStats);
        } catch (Exception e) {
            return AjaxResult.error("获取用户画像数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取信用分分布数据（无需权限）
     */
    @GetMapping("/stats/creditDistributionOpen")
    public AjaxResult getCreditDistributionOpen()
    {
        try {
            Map<String, Object> result = creditStatisticsService.getCreditDistribution();
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取信用分分布数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取服务使用趋势数据（无需权限）
     */
    @GetMapping("/stats/usageTrendOpen")
    public AjaxResult getServiceUsageTrendOpen(@RequestParam(required = false) String timeRange)
    {
        try {
            // 根据时间范围设置查询参数
            Date startDate = new Date();
            Date endDate = new Date();
            
            if ("week".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -7);
                startDate = cal.getTime();
            } else if ("month".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -1);
                startDate = cal.getTime();
            } else if ("quarter".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -3);
                startDate = cal.getTime();
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getServiceUsageTrend(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取服务使用趋势数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取地区分布数据（无需权限）
     */
    @GetMapping("/stats/regionDistributionOpen")
    public AjaxResult getRegionDistributionOpen()
    {
        try {
            Map<String, Object> result = creditStatisticsService.getRegionDistribution();
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取地区分布数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取收入统计数据（无需权限）
     */
    @GetMapping("/stats/revenueOpen")
    public AjaxResult getRevenueStatsOpen(@RequestParam(required = false) String timeRange)
    {
        try {
            // 根据时间范围设置查询参数
            Date startDate = new Date();
            Date endDate = new Date();
            
            if ("week".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -7);
                startDate = cal.getTime();
            } else if ("month".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -1);
                startDate = cal.getTime();
            } else if ("quarter".equals(timeRange)) {
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.MONTH, -3);
                startDate = cal.getTime();
            } else {
                // 默认查询最近30天
                Calendar cal = Calendar.getInstance();
                endDate = cal.getTime();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                startDate = cal.getTime();
            }
            
            Map<String, Object> result = creditStatisticsService.getRevenueStats(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取收入统计数据失败：" + e.getMessage());
        }
    }
} 